package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.LoginBean;
import com.ekuaitu.kuaitu.bean.SmsCodeBean;
import com.ekuaitu.kuaitu.utils.CheckRegexUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.zhy.autolayout.AutoRelativeLayout;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.login_return)
    ImageView loginReturn;
    @BindView(R.id.toolbar_signin)
    AutoRelativeLayout toolbarSignin;
    @BindView(R.id.login_phone)
    TextView loginPhone;
    @BindView(R.id.login_phoneNum)
    EditText loginPhoneNum;
    @BindView(R.id.login_getSms)
    TextView loginGetSms;
    @BindView(R.id.login_smsCode)
    EditText loginSmsCode;
    @BindView(R.id.login_protocol)
    TextView loginProtocol;
    @BindView(R.id.login_confirm)
    TextView loginConfirm;
    @BindView(R.id.progress_bar_login)
    RelativeLayout progressBarLogin;
    private PushAgent mPushAgent;
    private String phoneNum;
    private String smsCode;
    private Context mContext = this;
    private int seconds = 120;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (seconds > 0) {
                        loginGetSms.setText(seconds-- + "秒");
                        //每过1000毫秒发送消息
                        handler.sendEmptyMessageDelayed(0, 1000);
                    } else {
                        seconds = 120;
                        loginGetSms.setClickable(true);
                        loginGetSms.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        loginGetSms.setText("获取验证码");
                    }
                    break;
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }


    @Override
    public void initData() {
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
    }

    @OnClick({R.id.login_return, R.id.login_getSms, R.id.login_protocol, R.id.login_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_return:
                finish();
                break;
            case R.id.login_getSms:
                phoneNum = loginPhoneNum.getText().toString() + "";
                if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                    loginGetSms.setClickable(false);
                    sendSms(phoneNum);
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.inputPhoneNum), Toast.LENGTH_SHORT).setGravity(Gravity.CENTER, 0, 0).show();
                }
                break;
            case R.id.login_protocol:
                Intent intent = new Intent();
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "用户协议");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.USER_AGREEMENT);
                startActivity(intent);
                break;
            case R.id.login_confirm:
                MobclickAgent.onEvent(this, Constants.PHONE_VERIFICATION);
                startLocation();
                break;
        }
    }

    private void sendSms(String phoneNum) {
        progressBarLogin.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).sendSms(MyApplication.getInstance().getRequestFieldMap(), phoneNum).enqueue(new Callback<SmsCodeBean>() {
            @Override
            public void onResponse(Call<SmsCodeBean> call, Response<SmsCodeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBarLogin.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        ToastCompat.makeText(mContext, "验证码正在发送中...", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        //重发验证码倒计时
                        loginGetSms.setBackgroundColor(Color.parseColor("#C8C8C8"));
                        handler.sendEmptyMessage(0);
                    } else {
                        loginGetSms.setClickable(true);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<SmsCodeBean> call, Throwable t) {
                progressBarLogin.setVisibility(View.GONE);
                loginGetSms.setClickable(true);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                Log.i("neterror", "004" + t.toString());
            }
        });
    }

    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                progressBarLogin.setVisibility(View.VISIBLE);
                mLocationClient.startLocation();
            }
        } else {
            progressBarLogin.setVisibility(View.VISIBLE);
            mLocationClient.startLocation();
        }
    }

    private void login(String phoneNum, String sms, String longitude, String latitude) {
        String deviceToken = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.DEVICE_TOKEN);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).login(MyApplication.getInstance().getRequestFieldMap(), phoneNum, sms, longitude, latitude, deviceToken).enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.loginSuccess), Toast.LENGTH_SHORT).setGravity(Gravity.CENTER, 0, 0).show();
                        try {
                            mPushAgent.removeAlias(MyApplication.getInstance().getUid(), "USER", new UTrack.ICallBack() {
                                @Override
                                public void onMessage(boolean b, String s) {

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LoginBean.AttachmentBean.UserModelBean userModel = response.body().getAttachment().getUserModel();
                        MyApplication.getInstance().setUid(userModel.getId());
                        MyApplication.getInstance().setToken(userModel.getToken());
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.USER_PHONE_NUM, userModel.getPhoneNum());
                        SharedPreferencesUtils.getInstance(mContext).putStringValue("name", userModel.getName());
                        SharedPreferencesUtils.getInstance(mContext).putStringValue("status", userModel.getStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue("picture", userModel.getPicture() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue("isEnterprise", userModel.getIsEnterprise() + "");
                        SharedPreferencesUtils.getInstance(mContext).removeValue("avatarPath");
                        try {
                            mPushAgent.addAlias(MyApplication.getInstance().getUid(), "USER", new UTrack.ICallBack() {
                                @Override
                                public void onMessage(boolean b, String s) {

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Intent intent = new Intent(mContext, MainActivity.class);
                        intent.putExtra("isLogin", true);
                        startActivity(intent);
                        finish();
                    } else {
                        progressBarLogin.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                progressBarLogin.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).setGravity(Gravity.CENTER, 0, 0).show();
                Log.i("neterror", "005");
            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            MyApplication.getInstance().setAreaCode(aMapLocation.getCityCode());
            smsCode = loginSmsCode.getText().toString();
            phoneNum = loginPhoneNum.getText().toString();
            if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                if (!smsCode.equals("") && smsCode.length() == 4) {
                    login(phoneNum, smsCode, aMapLocation.getLatitude() + "", aMapLocation.getLongitude() + "");
                } else {
                    progressBarLogin.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, "请输入4位验证码", Toast.LENGTH_SHORT).setGravity(Gravity.CENTER, 0, 0).show();
                }
            } else {
                progressBarLogin.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.inputPhoneNum), Toast.LENGTH_SHORT).setGravity(Gravity.CENTER, 0, 0).show();
            }
        } else {
            mLocationClient.startLocation();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                progressBarLogin.setVisibility(View.VISIBLE);
                mLocationClient.startLocation();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                progressBarLogin.setVisibility(View.GONE);
                final KuaituDialog kuaituDialog = new KuaituDialog(LoginActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("您已拒绝定位权限");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                        startLocation();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

}
